#!/usr/bin/env python
# encoding: utf-8
"""
echoserver.py

Created by yanxu on 2006-11-08.
Copyright (c) 2006 80s Stdio. All rights reserved.
"""

from twisted.internet import reactor, protocol, defer
from twisted.protocols import basic
from twisted.internet.protocol import DatagramProtocol
from twisted.application import service, internet
import json

class EchoProtocol(basic.LineReceiver):

	def connectionMade(self):
		print "Got new client!"
		self.factory.clients.append(self)
		
	def connectionLost(self,reason):
		print "Lost a client!"
		self.factory.clients.remove(self)
		
	def lineReceived(self, line):
		if line == 'quit':
			self.sendLine("Goodbye.")
			self.transport.loseConnection( )
		else:
			# json.read(line)
			# self.sendLine("You IP: " + str(self.transport.getPeer()))
			# self.sendLine("You IP: " + str(self.transport.getPeer()[1]))
			# self.sendLine("You Host: " + str(self.transport.getHost()))
			# self.sendLine("You said: " + line)
			# self.sendLine("You said:", repr(line))
			for c in self.factory.clients:
				c.message(line)
				
	def message(self, message):
		# self.transport.write("Say:"+message + '\n')
		self.factory.test1(message
			).addErrback(lambda _: "Internal error in server"
			).addCallback(lambda m:(self.transport.write("Say:"+m + '\n'),))

class EchoServerFactory(protocol.ServerFactory):
	protocol  = EchoProtocol
	
class VideoCastProtocol(DatagramProtocol):
	def __init__ (self):
		self.targets = (('192.168.1.2', 1234),('192.168.1.3', 1234),)

	def datagramReceived(self, data, (host, port)):
		for target in self.targets:
			self.transport.write(data, target)

class FingerService(service.Service):
	
	def __init__(self, *args, **kwargs):
		self.parent.__init__(self, *args)
		reactor.callLater(30, self._read)
	def getUser(self):
		return defer.succeed("Find User")
	def getFactory(self):
		f = protocol.ServerFactory()
		f.protocol, f.getUser = EchoProtocol, self.getUser
		return f

factory = EchoServerFactory()
factory.clients = []

application = service.Application("echoserver", uid=1, gid=1)
f = FingerService()
serviceCollection = service.IServiceCollection(application)
internet.TCPServer(5001, f.getFactory()).setServiceParent(serviceCollection)
